import React, { useState, useRef, useEffect } from 'react';
import { Table, message, Space, Switch, Button, Popconfirm } from 'antd';
import { RightOutlined, DownOutlined, ReloadOutlined, FullscreenOutlined } from '@ant-design/icons';
import {
  getDepartmentInfo,
  getDepartmentList,
  getIsDepartment,
  getDepartmentNameList,
  deleteDepartment,
} from '@/services/departmentManage';
import Search from './Search';
import Modal from './Modal';
import { PageHeaderWrapper } from '@ant-design/pro-layout';

import './index.css';

export default function UserManage() {
  // modalVisible 保存modal的状态
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('');
  const [isFullScreen, setIsFullScreen] = useState(false);
  const [departmentListData, setDepartmentListData] = useState([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchKey, setSearchKey] = useState();
  const [id, setId] = useState();
  const [loading, setLoading] = useState(true);
  const [modalData, setModalData] = useState({});
  const [departmentNameList, setDepartmentNameList] = useState([]);
  const [upadteAid, setUpdateAid] = useState();

  //获取部门列表
  const getDepartmentListData = async () => {
    const msg = await getDepartmentList({ searchKey, id, page, pageSize });
    setDepartmentListData(msg);
    setLoading(false);
  };

  //执行一次
  useEffect(() => {
    setLoading(true);
    getDepartmentListData();
  }, [page, pageSize, id, searchKey]);

  //新增部门
  const addDepartment = async () => {
    setUpdateAid();
    setModalTitle('新增');
    const msg = await getDepartmentNameList();
    setDepartmentNameList(msg);
    setModalVisible(true);
  };

  // 修改部门
  const updateDepartment = async (aid) => {
    const msg1 = await getDepartmentInfo({ aid });
    setModalData(msg1);
    const msg2 = await getDepartmentNameList({ aid });
    setDepartmentNameList(msg2);
    setModalTitle('修改');
    setUpdateAid(aid);
    setModalVisible(true);
  };

  //关闭modal
  const updateModalVisible = () => {
    setModalVisible(false);
    setModalData({});
  };

  // 确定删除部门
  const confirm = async (aid) => {
    message.success('Click on Yes');
    await deleteDepartment({ aid });
    setLoading(true);
    getDepartmentListData();
  };

  // 取消删除部门
  function cancel() {
    message.error('Click on No');
  }

  // 刷新表格
  const Refresh = () => {
    setId();
    setPage(1);
    setSearchKey();
    setLoading(true);
    getDepartmentListData();
  };

  //table全屏展示
  const FullScreen = () => {
    var dom = document.getElementById('div1'); //绑定想要全屏的组件
    if (!isFullScreen) {
      dom.webkitRequestFullScreen(); //进入全屏
      setIsFullScreen(!isFullScreen);
    } else {
      dom = document;
      dom.webkitCancelFullScreen(); //退出全屏
      setIsFullScreen(!isFullScreen);
    }
  };

  //当鼠标移入刷新、全屏按钮是改变按钮颜色
  const changeColor0 = useRef();
  const changeColor1 = useRef();
  const mouseMoveColor = (changeColor) => {
    return () => {
      var dom = document.getElementById(changeColor.current.id);
      dom.style.color = '#1890FF';
    };
  };

  //当鼠标移出刷新、全屏按钮是改变按钮颜色
  const mouseLeaveColor = (changeColor) => {
    return () => {
      var dom = document.getElementById(changeColor.current.id);
      dom.style.color = 'black';
    };
  };

  //保存是否启用状态
  const onChange = (aid) => {
    getIsDepartment({ aid });
  };

  //改变page和pageSize的回调
  const pageChange = async (a, b) => {
    setPage(a);
    setPageSize(b);
  };

  //搜索部门
  const searchHandle = (values) => {
    setSearchKey(values.searchKey);
    setId(values.id);
    setPage(1);
    setPageSize(10);
  };

  // 设置table的行
  const columns = [
    {
      title: '部门名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <span style={{ paddingLeft: '10px' }}>{text}</span>,
    },
    {
      title: '部门编号',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '员工数',
      dataIndex: 'number',
      key: 'number',
    },
    {
      title: '是否启用',
      dataIndex: 'isEnable',
      key: 'isEnable',
      render: (text, record) => {
        return (
          <Switch
            checkedChildren="是"
            unCheckedChildren="否"
            key={record.isEnable}
            defaultChecked={record.isEnable}
            onChange={() => {
              onChange(record.aid);
            }}
          />
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (text, record) => {
        //判断部门是否可以删除
        var disabled = false;
        var pointerEvent = '';
        if (!record.isDelete) {
          disabled = true;
          pointerEvent = 'none';
        }
        return (
          <Space>
            <a
              onClick={() => {
                updateDepartment(record.aid);
              }}
            >
              修改
            </a>
            <Popconfirm
              title="你确定要删除该项数据吗？？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                confirm(record.aid);
              }}
              onCancel={cancel}
            >
              <a disabled={disabled} style={{ pointerEvents: pointerEvent }}>
                删除
              </a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <Search searchHandle={searchHandle} Refresh={Refresh} />
      <div id="div1">
        <div id="tableHead">
          <div id="div2">
            <span id="title">部门列表</span>
            <span id="total">{departmentListData.departmentNumbers}</span>总部门
          </div>
          <div id="btns">
            <Button
              id="addBtn"
              type="primary"
              onClick={() => {
                addDepartment();
              }}
            >
              新增
            </Button>
            <ReloadOutlined
              id="btnReload"
              ref={changeColor0}
              id="btnReload"
              onMouseMove={mouseMoveColor(changeColor0)}
              onMouseOut={mouseLeaveColor(changeColor0)}
              onClick={Refresh}
            />
            <FullscreenOutlined
              ref={changeColor1}
              id="fullScreen"
              onMouseMove={mouseMoveColor(changeColor1)}
              onMouseOut={mouseLeaveColor(changeColor1)}
              onClick={FullScreen}
            />
          </div>
        </div>

        <Table
          id="Table"
          dataSource={departmentListData.departmentList || []}
          rowKey="aid"
          columns={columns}
          pagination={{
            current: page,
            total: departmentListData.rowNumber || 0,
            showTotal: false,
            pageSize: pageSize,
            hideOnSinglePage: false,
            showSizeChanger: true,
            pageSizeOptions: [1, 2, 3, 4, 5, 10],
            onChange: pageChange,
          }}
          loading={loading}
          expandable={{
            expandIcon: ({ expanded, onExpand, record }) =>
              record.children ? (
                expanded ? (
                  <DownOutlined onClick={(e) => onExpand(record, e)} />
                ) : (
                  <RightOutlined onClick={(e) => onExpand(record, e)} />
                )
              ) : (
                <span style={{ paddingLeft: '13px' }} />
              ),
          }}
        />
      </div>

      <Modal
        modalVisible={modalVisible}
        updateModalVisible={updateModalVisible}
        modalTitle={modalTitle}
        modalData={modalData}
        departmentNameList={departmentNameList}
        updateAid={upadteAid}
        Refresh={Refresh}
      />
    </PageHeaderWrapper>
  );
}
